//*******************************//
//<xml fileName="CUserServlet.java" ?>
//<author>申鱼川</author>
//<dateTime>2014-02-23</dateTime>
//</xml>
//*******************************//
package youleche.com.controler.servlet;

import java.beans.IntrospectionException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;

import youleche.com.business.BUser;
import youleche.com.common.ParamConfigParameters;
import youleche.com.common.asynchronous.AsynFactory;
import youleche.com.common.email.MailFactory;
import youleche.com.controler.servlet.common.UlecheHttpServlet;
import youleche.com.factory.MLLogFactory;
import youleche.com.model.MUser;
import youleche.com.util.AESEncryptAndDecrypt;
import youleche.com.util.JsonHelper;
import youleche.com.util.UnicodeUtil;

/**
 * 用户Servlet
 */
public class CUserServlet extends UlecheHttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * Session
	 */
	private HttpSession session; 
	
	/**
	 * 用户处理类
	 */
	private BUser userHander = null;
       
    /**
     * @see CUserServlet构造类
     */
    public CUserServlet() {
        super();
    }

    /**
     * 初始化方法
     */
    @Override
    public void init() throws ServletException {
    	this.userHander = new BUser();
    }

	/**
	 * doPost方法
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		/*
		 * type用请求类型，0登录，1注册（发送激活邮件），2邮件确认并修改（如果存在）或保存（如果不存在）用户信息
		 */
		int type = Integer.parseInt(request.getParameter("type"));
		String message = "";
		switch(type){
			case 0 :
				//登录
				message = this.login(request, response);				
				break;				
			case 1 :
				//注册
				message = this.register(request, response);		
				break;
			case 2 :
				//邮箱验正成功，用户修改信息
				break;
			case 3 :
				//判断用户是否登录
				this.isLogin(request, response);
				break;
			case 4:
				///判断邮箱是否注册
				this.isRegister(request, response);
				break;
			case 5: 
				//重新发送邮件
				this.afreshSendEmail(request, response);
				break;
			case 6 :
				//管理员登陆
				message = this.adminLogin(request, response);
				break;
			case 7 :
				//用户激活校验
				this.validateAct(request, response);
				break;
			case 8 :
				//用户激活
				this.act(request, response);
				break;
			case 9 :
				//注销
				message = this.exit(request, response);
				break;
			case 10 :
				//登陆成功返回用户ID
				message = this.loginReturnSellerId(request, response);
				break;
			case 11:
				//根据用户名获取用户ID
				message = this.getUserIdByUserName(request, response);
				break;
			case 12:
				//用户成为商家
				message = this.becomeSeller(request, response);
				break;
			case 13 :
				//判断用户名是否存在
				message = this.isExistUserName(request, response);
				break;
			case 14 :
				//判断电话号码是否存在
				message = this.isExisPhoneNum(request, response);
				break;
			case 15:
				//添加用户信息
				message = this.addUser(request, response);
			case 16:
				//判断邮箱是否存在
				message = this.isExistEmail(request, response);
		}
		
		super.response(response, message);
	}
	
	/**
	 * 判断电话号码是否存在
	 * @param request 请求
	 * @return 返回页面参数
	 */
	private String isExisPhoneNum(HttpServletRequest request, HttpServletResponse response){
		String phone = request.getParameter("phone");		
		BUser handler = new BUser();
		try {
			String userName = handler.getUserNameByPhoneNum(phone);
			if(!"".equals(userName)){
				return "1";
			}
		} catch (Exception e) {
			return "0";
		}
		
		return "0";
	}
	
	
	
	/**
	 * 判断邮箱是否存在
	 * @param request 请求
	 * @return 返回页面参数
	 */
	private String isExistEmail(HttpServletRequest request, HttpServletResponse response){
		String email = request.getParameter("email");	
		ParamConfigParameters paramConfig = new ParamConfigParameters();
		String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
		try {
			String enAccount = AESEncryptAndDecrypt.encrypt(email, loginCode_KEY);		
			BUser handler = new BUser();			
			if(handler.getUserNameByEmailAccount(enAccount)!= null){
				return "1";
			}
		} catch (Exception e) {
			return "0";
		}
		
		return "0";
	}
	
	/**
	 * 判断用户名是否存在
	 * @param request 请求
	 * @return 返回页面参数
	 */
	private String isExistUserName(HttpServletRequest request, HttpServletResponse response){
		String userName = request.getParameter("userName");		
		BUser handler = new BUser();
		try {
			if(handler.getUserByUserName(userName) != null){
				return "1";
			}
		} catch (Exception e) {
			return "0";
		}
		
		return "0";
	}
	
	/**
	 * 用户成为商家
	 * @param request 请求
	 * @return 返回页面参数
	 */
	private String becomeSeller(HttpServletRequest request, HttpServletResponse response){
		String userName = request.getParameter("userName");		
		String email = request.getParameter("email");		
		String phone = request.getParameter("phone");	
		BUser handler = new BUser();
		try {
			boolean boolUser = handler.getUserByUserName(userName) == null ? true : false;
			boolean boolEmail = handler.getUserNameByEmailAccount(email) == "" ? true : false;
			boolean boolPhone = handler.getUserNameByPhoneNum(phone) == "" ? true : false;
			if(boolUser & boolEmail & boolPhone){
				ParamConfigParameters paramConfig = new ParamConfigParameters();
				String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
				MUser user = new MUser();
				user.setUserName(userName);
				user.setPhoneNum(phone);
				user.setEmail(AESEncryptAndDecrypt.encrypt(email, loginCode_KEY));
				if(handler.register(user) > 0){
					return ""+handler.becomeSellerByEmail(AESEncryptAndDecrypt.encrypt(email, loginCode_KEY))+"";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "0";
	}
	
	
	/**
	 * 根据用户名获取用户ID
	 * @param request 请求
	 * @return 返回页面参数
	 */
	private String getUserIdByUserName(HttpServletRequest request, HttpServletResponse response){
		String userName = request.getParameter("userName");		
		BUser hanlder = new BUser();
		MUser user;
		try {
			user = hanlder.getUserByUserName(userName);
			return user.getId();
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
	}
	
	/**
	 * 登陆成功返回用户ID
	 * @param request 请求
	 * @return 返回页面参数
	 */
	private String loginReturnSellerId(HttpServletRequest request, HttpServletResponse response){
		String loginCode = request.getParameter("userName");
		String password = request.getParameter("password");
		int loginType = this.parseLoginType(loginCode);//登录方式（0-用户名，1-手机号码，2-邮箱）
		boolean result = this.login(loginType, loginCode, password);
		if(result){ 
			String userName = this.getUserNameByLoginTypeAndLoginAccount(loginType, loginCode);			
			this.setCookieAndSession(request, response, userName, password);
			BUser hanlder = new BUser();
			MUser user;
			try {
				user = hanlder.getUserByUserName(userName);
				return user.getId();
			} catch (Exception e) {
				e.printStackTrace();
				return "";
			}
		}else{
			return "";
		}
	}
	
	/**
	 * 注销
	 * @param request
	 * @param response
	 */
	private String exit(HttpServletRequest request, HttpServletResponse response){
		String userName = request.getParameter("u");
		HttpSession session = request.getSession(false);//防止创建Session
		if(session == null){
			return "1";
		}
		
		if(UnicodeUtil.isContainsChinese(userName)){
			try {
				userName = 	java.net.URLEncoder.encode(userName,"utf-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		
		session.removeAttribute(userName);
		
		Cookie cookie_u = new Cookie("youleche.u", null); 
		cookie_u.setMaxAge(-1);
		response.addCookie(cookie_u); 
		
		Cookie cookie_s = new Cookie("youleche.s", null); 
		cookie_s.setMaxAge(-1);
		response.addCookie(cookie_s); 
		
		return "1";
	}
	
	/**
	 * /用户激活
	 * @param request
	 * @param response
	 */
	private void act(HttpServletRequest request, HttpServletResponse response){
		try {
			Gson gson = new Gson();
			MUser user = (MUser)gson.fromJson(JsonHelper.readJSONString(request), MUser.class);
			
			ParamConfigParameters paramConfig = new ParamConfigParameters();
			String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
			user.setUserPassword(AESEncryptAndDecrypt.encrypt(user.getUserPassword(), loginCode_KEY));
			user.setEmail(AESEncryptAndDecrypt.encrypt(user.getEmail(), loginCode_KEY));
			BUser handler = new BUser();
			if(handler.actUserInfo(user) > 0){
				this.setCookieAndSession(request, response, user.getUserName(), user.getUserPassword());
				super.response(response, "1");
			}else{
				super.response(response, "0");	
			}
		} catch (Exception e) {
			super.response(response, "0");
			e.printStackTrace();
		} 
	}
	
	/**
	 * /用户激活校验
	 * @param request
	 * @param response
	 */
	private void validateAct(HttpServletRequest request, HttpServletResponse response){
		String email = request.getParameter("email");
		String r = request.getParameter("r");
		BUser handler = new BUser();
		try {
			ParamConfigParameters paramConfig = new ParamConfigParameters();
			String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
			if(r.equals(handler.getUserNameByEmailAccount(AESEncryptAndDecrypt.encrypt(email, loginCode_KEY)))){
				super.response(response, "1");
			}else{
				super.response(response, "0");
			}
		} catch (Exception e) {
			super.response(response, "0");
			e.printStackTrace();
		}
	}
	
	/**
	 * 管理员登陆
	 * @param request
	 * @param response
	 */
	private String adminLogin(HttpServletRequest request, HttpServletResponse response){
		String msg =  this.login(request, response);
		try {
			if("{\"data\": \"true\"}".equals(msg)){
				////判断有管理员权限没
				String loginName = request.getParameter("userName");
				int loginType = this.parseLoginType(loginName);//登录方式（0-用户名，1-手机号码，2-邮箱）
				BUser handler = new BUser();
				if(loginType != 0){
					loginName = this.getUserNameByLoginTypeAndLoginAccount(loginType, loginName);	
				}
				
				MUser user = handler.getUserByUserName(loginName);
				String a3_limit = user.getA3();
				if("".equals(a3_limit)){
					a3_limit = "0";
				}
				
				int limit = Integer.parseInt(a3_limit);
				if(limit < 3){
					msg = super.getJsonMsg("false");
				}
			}
		} catch (Exception e) {
			msg = super.getJsonMsg("false");
			e.printStackTrace();
			MLLogFactory.exceptionLog("管理员登陆出现错误", "管理员登陆异常", e.getMessage(), request.getRemoteAddr());
		}
		
		MLLogFactory.accLog("管理员登陆", "登陆返回的值", msg, request.getRemoteAddr());
		
		return msg;
	}
	
	/**
	 * 重新发送邮件
	 * @param request 请求
	 * @param response 响应
	 */
	private void afreshSendEmail(HttpServletRequest request, HttpServletResponse response){
		String email = request.getParameter("email");
		MailFactory factory = new MailFactory();
		//根据email获取随机码
		
		if("ok".equals(factory.sendMail(email, "0123"))){
			System.out.println("重新发送邮件成功");
			super.response(response, "重新发送邮件成功");
		}else{
			super.response(response, "重新发送邮件失败");
		}
	}
	
	/**
	 * 判断用户是否注册
	 * @param request 请求
	 * @param response 响应
	 */
	private void isRegister(HttpServletRequest request, HttpServletResponse response){
		String email = request.getParameter("email");
		BUser handler = new BUser();
		try {
			ParamConfigParameters paramConfig = new ParamConfigParameters();
			String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
			String result = handler.isRegitered(AESEncryptAndDecrypt.encrypt(email, loginCode_KEY)) == true ? "1" : "0";
			super.response(response, result);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 用户是否登录
	 * @param request 请求
	 * @param response 响应
	 */
	private void isLogin(HttpServletRequest request, HttpServletResponse response){
		ParamConfigParameters paramConfig = new ParamConfigParameters();
		String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
		this.session = request.getSession();
		Map<String, String> cookiesInfo = JsonHelper.readJsonKeyValues(request);
		String cookieValue ="";
		Set<Map.Entry<String, String>> set = cookiesInfo.entrySet();
		for (Iterator<Map.Entry<String, String>>  it = set.iterator(); it.hasNext();) {
			Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
			if("args1".equals(entry.getKey())){
				cookieValue = entry.getValue();
				break;
			}	
		}
		
		String userName = "";
		try {
			userName = AESEncryptAndDecrypt.decrypt(cookieValue, loginCode_KEY).split("^")[0];
		} catch (Exception e) {
			e.printStackTrace();
			super.response(response, "false");
		}
		String sessionKey = (String) session.getAttribute(""+userName+"");
		if("".equals(cookieValue) || "".equals(sessionKey)){
			super.response(response, "false");
			return;
		}
		
		if(cookieValue.equals(sessionKey)){
			super.response(response, "true");
		}else{
			super.response(response, "false");
		}
	
	}
	
	/**
	 * 注册
	 * @param email 邮箱
	 * @return 返回提示
	 */
	private String register(HttpServletRequest request, HttpServletResponse response){		
		String email = request.getParameter("email");
		Random random = new Random();
		String rendomStr = "";
		for (int i = 0; i < 6; i++) {
			rendomStr += random.nextInt(9);
		}
		if(this.isRegister(email, rendomStr)){
			MailFactory.getInstance().sendMail(email, rendomStr);
			return super.getJsonMsg("true");
		}else{
			return super.getJsonMsg("false");
		}
	}

	/**
	 * 添加用户信息
	 * @return 返回提示
	 */
	private String addUser(HttpServletRequest request, HttpServletResponse response){		
		MUser user = (MUser) JsonHelper.getObjectByJsonStringAndGson(request, MUser.class);
		ParamConfigParameters paramConfig = new ParamConfigParameters();
		String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
		try {
		if(UnicodeUtil.isContainsChinese(user.getUserName())){
			user.setUserName(java.net.URLEncoder.encode(user.getUserName(),"utf-8"));
		}
		
		user.setUserPassword(AESEncryptAndDecrypt.encrypt("sdk_mlc", loginCode_KEY));
		
		user.setEmail(AESEncryptAndDecrypt.encrypt(user.getEmail(), loginCode_KEY));
		user.setA3("2");
		user.setA3("000000");
		BUser handler = new BUser();
		if(handler.register(user) > 0 && handler.actUserInfo(user) > 0){
			this.setCookieAndSession(request, response, user.getUserName(), user.getUserPassword());
			return "1";
		}
		} catch (Exception e) {
			e.printStackTrace();
			MLLogFactory.exceptionLog("添加用户信息发生异常", "添加用户信息", e.getMessage(), "127.0.0.1");
			return "0";
		}
		
		return "0";
	}
	
	/**
	 * 发送验证邮件
	 *@param email email地址
	 */
	public void sendActivateEmail(String email) {
		//AsynFactory.AsynSendEmail(email);
		
	}
	
	/**
	 * 是否注册成功
	 * @param email 邮箱
	 * @return 返回注册是否成功
	 */
	private boolean isRegister(String email, String random){
		MUser user = new MUser();
		try {
			ParamConfigParameters paramConfig = new ParamConfigParameters();
			String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
			String encryEmail = AESEncryptAndDecrypt.encrypt(email, loginCode_KEY);
			user.setEmail(encryEmail);
			if(this.userHander.isRegitered(encryEmail)){
				return false;
			}
			user.setA3("1");//注册用户（非激活）
			user.setUserName(random);
			
			return this.userHander.register(user) > 0 ? true : false;
		} catch (Exception e) {
			MLLogFactory.exceptionLog("注册失败", "注册失败", e.getMessage(), "127.0.0.1");
			return false;
		}
	}
	
	/**
	 * 登陆
	 * @param request 请求
	 * @return 返回页面参数
	 */
	private String login(HttpServletRequest request, HttpServletResponse response){
		String loginCode = request.getParameter("userName");
		String password = request.getParameter("password");
		int loginType = this.parseLoginType(loginCode);//登录方式（0-用户名，1-手机号码，2-邮箱）
		boolean result = this.login(loginType, loginCode, password);
		
		if(result){ 
			String userName = this.getUserNameByLoginTypeAndLoginAccount(loginType, loginCode);			
			this.setCookieAndSession(request, response, userName, password);
			return super.getJsonMsg("true");
		}else{
			return super.getJsonMsg("false");
		}
	}
	
	/**
	 * 登陆
	 * @param loginType 账号类型
	 * @param loginCode 账号
	 * @param password 密码
	 * @return 登陆是否成功
	 */
	private boolean login(int loginType, String loginCode, String password){
		
		try {
			return this.userHander.login(this.SetUserLoginMessage(loginType, loginCode, password));
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return false;
	}
	/**
	 * 根据登陆账号和账号类型获取用户名
	 * @param loginType 账号类型（1-手机，2-邮箱）
	 * @param account 账号
	 * @return 用户名
	 */
	private String getUserNameByLoginTypeAndLoginAccount(int loginType, String account){
		try {
			switch(loginType){
				case 0:
					return account;
				case 1:
					return this.userHander.getUserNameByPhoneNum(account);
				case 2:
					ParamConfigParameters paramConfig = new ParamConfigParameters();
					String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
					String enAccount = AESEncryptAndDecrypt.encrypt(account, loginCode_KEY);
					return this.userHander.getUserNameByEmailAccount(enAccount);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return "";
	}
	
	/**
	 * 设置cookie和session
	 * @param request request请求
	 * @param response response响应
	 * @param userName 用户名
	 * @param pass  密码
	 */
	private void setCookieAndSession(HttpServletRequest request, HttpServletResponse response, String userName, String pass){

		ParamConfigParameters paramConfig = new ParamConfigParameters();
		String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
		try {			
			super.setSession(request, userName, AESEncryptAndDecrypt.encrypt(userName + "^" + pass, loginCode_KEY));
			super.setCookie(response, "youleche.u", userName);
			super.setCookie(response, "youleche.s", AESEncryptAndDecrypt.encrypt(userName + "^" + pass, loginCode_KEY));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 设置用户登录名
	 * @param loginType 登录方式（0-用户名，1-手机号码，2-邮箱）
	 * @param loginCode 用户名or手机号码or邮箱
	 * @param password 登录密码
	 * @return 返回用户对象
	 * @throws Exception 
	 */
	private MUser SetUserLoginMessage(int loginType, String loginCode, String password) throws Exception{
		MUser user = new MUser();

		ParamConfigParameters paramConfig = new ParamConfigParameters();
		String loginCode_KEY = paramConfig.getParameter("loginCode_KEY");
		if(loginType == 2){
			loginCode = AESEncryptAndDecrypt.encrypt(loginCode, loginCode_KEY);				
		}	
		
		user.setUserName(loginCode);
		user.setPhoneNum(loginCode);
		user.setEmail(loginCode);
		user.setUserPassword(AESEncryptAndDecrypt.encrypt(password, loginCode_KEY));
		return user;
	}
	
	/**
	 * 根据用户名解析登陆类型
	 * @param userName 用户名
	 * @return  返回登录方式（0-用户名，1-手机号码，2-邮箱）
	 */
	private int parseLoginType(String userName){
		if(userName.contains("@")){
			return 2;
		}else if(userName.matches("^[1][358]\\d{9}$")){
			return 1;
		}else{
			return 0;
		}
	}

}
